#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// 共享变量
int shared_variable = 0;

// 互斥锁
pthread_mutex_t mutex;

// 线程函数
void* thread_function(void* arg) {
    int thread_id = *(int*)arg;

    for (int i = 0; i < 50; i++) {
        // 锁定互斥锁
        pthread_mutex_lock(&mutex);

        // 修改共享变量
        shared_variable++;
        printf("Thread %d incremented shared_variable to %d\n", thread_id, shared_variable);
        sleep(10);
        // 释放互斥锁
        pthread_mutex_unlock(&mutex);

        // 模拟工作负载
        sleep(1);
    }

    return NULL;
}

int main() {
    pthread_t threads[2];
    int thread_ids[2] = {1, 2};

    // 初始化互斥锁
    if (pthread_mutex_init(&mutex, NULL) != 0) {
        perror("Mutex initialization failed");
        return 1;
    }

    // 创建两个线程
    for (int i = 0; i < 2; i++) {
        if (pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]) != 0) {
            perror("Thread creation failed");
            return 1;
        }
    }

    // 等待线程结束
    for (int i = 0; i < 2; i++) {
        if (pthread_join(threads[i], NULL) != 0) {
            perror("Thread join failed");
            return 1;
        }
    }

    // 销毁互斥锁
    pthread_mutex_destroy(&mutex);

    printf("Final value of shared_variable: %d\n", shared_variable);

    return 0;
}


